package com.beta.cust.bind.webapi.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * @author gwqin
 * @description
 * @date 2022-07-26 10:50
 */
@Slf4j
public class ResponseUtils {

    private static void writerJsonInfo(HttpServletResponse response, String content) {
        response.setHeader("Content-Type", "application/json");
        responseOutPutStream(response, content);
    }

    public static void writerHtml(HttpServletResponse response, String html) {
        response.setHeader("Content-Type", "text/html;charset=utf-8");
        responseOutPutStream(response, html);
    }

    private static void responseOutPutStream(HttpServletResponse response, String str) {
        try {
            ServletOutputStream out = response.getOutputStream();
            out.write(str.getBytes());
            out.flush();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 往客户端写回响应信息
     *
     * @param response
     * @param status   状态码
     * @param msg      描述信息
     */
    public static void writeResponse(HttpServletResponse response, int status, String msg) {
        // response.setStatus(status);
        JSONObject jo = new JSONObject();
        jo.put("code", status);
        jo.put("msg", msg);
        writerJsonInfo(response, jo.toJSONString());
    }

    public static void writeResponse(HttpServletResponse response, int status, String msg, Object data) {
        // response.setStatus(status);
        JSONObject jo = new JSONObject();
        jo.put("code", status);
        jo.put("msg", msg);
        jo.put("data", data);
        writerJsonInfo(response, jo.toJSONString());
    }
}
